package com.sgu6.sgu6_machine.ui.fragment;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.enums.MachineStatusEnum;
import com.sgu6.middleware.enums.MillActionEnum;
import com.sgu6.middleware.event.MakeRiceEvent;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.netty.container.Machine;
import com.sgu6.netty.utils.NettyHelper;
import com.sgu6.redis.cache.OrderCache;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.MakeRecordDto;
import com.sgu6.sgu6_machine.event.FinishOrderEvent;
import com.sgu6.sgu6_machine.event.MillStatusEvent;
import com.sgu6.sgu6_machine.event.WeightEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.task.MillTimeoutRunnable;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MillF extends BaseF {

    public static final String TAG = MillF.class.getSimpleName();

    private Unbinder unbinder;

    @BindView(R.id.tvMillDetail)
    TextView tvMillDetail;
    @BindView(R.id.tvMillNotice)
    TextView tvMillNotice;
    @BindView(R.id.progress)
    ImageView ivProgress;


    private MediaPlayer player;
    private MachineP machineP = new MachineP();
    private Handler handler = new Handler();
    private MillTimeoutRunnable runnable = new MillTimeoutRunnable();
    private Thread thread = new Thread();


    public static MillF newInstance(String params) {
        return new MillF();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_mill, container, false);
        unbinder = ButterKnife.bind(this, v);
        Glide.with(requireContext()).load(R.drawable.milling).into(ivProgress);
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMakeRiceEvent(MakeRiceEvent event) {
        MachineContainer.orderInfoCacheDto.setMakeNum(event.makeNo);
        MachineContainer.orderInfoCacheDto.setOrderNo(event.orderNo);
        String info = String.format("请稍等,正在为您碾 [ %d ] 斤" + MachineContainer.riceName, event.makeNo);
        tvMillNotice.setText(null);
        tvMillDetail.setText(info);
        //发送碾米完成通知
        //MachineContainer.orderInfoCacheDto.setFinishNo(1);
        //finishMill();

        handler.postDelayed(runnable, event.makeNo * MachineContainer.machineConfigDto.millTimeOut * 1000);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler = null;
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @SuppressLint("DefaultLocale")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMillStatusEvent(MillStatusEvent event) {

        if (event.status.equals(MillActionEnum.碾米中.code())) {
            tvMillDetail.setText(String.format("请稍等,正在碾米中\n%d / %d", MachineContainer.orderInfoCacheDto.getFinishNo(), MachineContainer.orderInfoCacheDto.getMakeNum()));
        } else if (event.status.equals(MillActionEnum.下米.code())) {
            play(R.raw.baidu_packing);
            tvMillDetail.setText("正在下米");
        } else if (event.status.equals(MillActionEnum.拉膜.code())) {
            tvMillDetail.setText("正在包装");
        } else if (event.status.equals(MillActionEnum.封膜.code())) {
//            tvMillDetail.setText("正在封膜");
            int finishNo = MachineContainer.orderInfoCacheDto.getFinishNo();
            MachineContainer.orderInfoCacheDto.setFinishNo(finishNo + 1);
            tvMillDetail.setText(String.format("请稍等,正在碾米中\n%d / %d", MachineContainer.orderInfoCacheDto.getFinishNo(), MachineContainer.orderInfoCacheDto.getMakeNum()));
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    OrderCache.updateOrder(MachineContainer.orderInfoCacheDto.getOrderNo(), MachineContainer.orderInfoCacheDto.getFinishNo());
                    int no1 = MachineContainer.orderInfoCacheDto.getFinishNo();
                    int no2 = MachineContainer.orderInfoCacheDto.getMakeNum();
                    if (MachineContainer.orderInfoCacheDto.getFinishNo() == MachineContainer.orderInfoCacheDto.getMakeNum()) {
                        EventBus.getDefault().post(new FinishOrderEvent());
                    } else {
                        Log.i(TAG, "onMillStatusEvent: ");
                    }
                }
            });
            thread.start();
        } else if (event.status.equals(MillActionEnum.出货.code())) {

        } else if (event.status.contains(MillActionEnum.碾米一包完成.code())) {

        }
    }

    @SuppressLint("DefaultLocale")
    public void finishMill() {
        //移除碾米超时任务
        handler.removeCallbacks(runnable);
        if (MachineContainer.orderInfoCacheDto.getFinishNo() == MachineContainer.orderInfoCacheDto.getMakeNum()) {
            tvMillDetail.setText(String.format("碾米完成，共 [ %d ] 斤鲜米，请从取米口及时取出。", MachineContainer.orderInfoCacheDto.getFinishNo()));
        } else {
            tvMillDetail.setText(String.format("已完成 [ %d ] 斤%s，\n有 [ %d ] 斤将退款，\n请从取米口及时取出。", MachineContainer.orderInfoCacheDto.getFinishNo(), MachineContainer.riceName, MachineContainer.orderInfoCacheDto.getMakeNum() - MachineContainer.orderInfoCacheDto.getFinishNo()));
        }


        play(R.raw.baidu_finish_qumi);


        if (MachineContainer.isPay) {
            NettyHelper.postMsgWithFinishOrderReq(MachineContainer.orderInfoCacheDto.getBarnId(), MachineContainer.machineConfigDto.machineNo, MachineContainer.orderInfoCacheDto.getOrderNo(), MachineContainer.orderInfoCacheDto.getFinishNo(), MachineContainer.orderInfoCacheDto.getMakeNum());
        } else {
//            machineP.postBackMakeRecord(new MakeRecordDto(MachineContainer.machineConfigDto.machineNo, MachineContainer.orderInfoCacheDto.getBarnId(), MachineContainer.machineConfigDto.packageWeight, MachineContainer.orderInfoCacheDto.getMakeNum(), MachineContainer.orderInfoCacheDto.getFinishNo()));
        }
        //清除上次的碾米记录
        MachineContainer.clearOrderCache();
        MachineContainer.setMachineStatus(MachineStatusEnum.待机.code());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWeightEvent(WeightEvent event) {
        MachineContainer.orderInfoCacheDto.setFinishNo(event.finishNo);
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.出米.code()));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishEvent(FinishOrderEvent event) {
        finishMill();
    }


    public void play(int id) {
        ThreadManager.getThreadPollProxy().execute(() -> {
            try {
                if (player != null && player.isPlaying()) {
                    player.pause();
                    player.reset();
                }
                player = MediaPlayer.create(requireContext(), id);
                player.start();//开始或恢复播放
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
